package com.resou.reader.mine.userinfo;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.resou.reader.R;
import com.resou.reader.api.ApiImp;
import com.resou.reader.api.entry.LoginData;
import com.resou.reader.api.entry.Result;
import com.resou.reader.api.service.UserService;
import com.resou.reader.base.v.BaseActivity;
import com.resou.reader.commom.Constant;
import com.resou.reader.mine.IView.IUserInfoView;
import com.resou.reader.mine.IView.UserInstance;
import com.resou.reader.mine.login.BirthdayActivity;
import com.resou.reader.mine.login.GenderChoiceFragment;
import com.resou.reader.mine.login.NicknameSettingActivity;
import com.resou.reader.mine.login.PhoneBindActivity;
import com.resou.reader.mine.login.UserHeadImgChoiceFragment;
import com.resou.reader.mine.presenter.UserInfoPresenter;
import com.resou.reader.utils.ConstellationUtils;
import com.resou.reader.utils.PreferenceUtil;
import com.resou.reader.utils.ToastUtil;
import com.resou.reader.utils.eventbus.RefreshStoreEvent;
import com.resou.reader.utils.eventbus.UpdateUserIconEvent;
import com.resou.reader.view.CircleImageView;
import com.resou.reader.view.Loading;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.raphets.roundimageview.RoundImageView;

import java.io.File;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.functions.Action;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

public class UserInfoActivity extends BaseActivity<UserInfoPresenter> implements IUserInfoView, UserHeadImgChoiceFragment.CallBackValue {

    @BindView(R.id.user_info_head)
    RoundImageView mUserHead;
    @BindView(R.id.nick_name_text)
    TextView mNickName;
    @BindView(R.id.user_gender_text)
    TextView mGender;
    @BindView(R.id.user_birthday_text)
    TextView mBirthday;
    @BindView(R.id.user_id_text)
    TextView mId;
    @BindView(R.id.user_bind_text)
    TextView mBindPhone;
    @BindView(R.id.user_login_type_text)
    TextView mLoginType;
    @BindView(R.id.user_level_text)
    TextView mLevel;
    String birthday = "";
    private GenderChoiceFragment mGenderChoiceFragment;
    private UserHeadImgChoiceFragment mUserHeadImgChoiceFragment;

    @Override
    protected void initView() {
        refreshView();
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        isNetwork();
    }

    /**
     * 用户修改头像后同步刷新
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(UpdateUserIconEvent event) {
        Loading.getInstance().dismiss();
        if (PreferenceUtil.getInstance(this).getUserIcon() != null) {
            mUserHead.setImageURI(Uri.parse(PreferenceUtil.getInstance(this).getUserIcon()));
        }
    }

    @Override
    protected void retryRefreshData() {

    }


    private void refreshView() {

        LoginData loginData = UserInstance.getLoginData();
        // 头像
        if (loginData.getHead_pic() != null) {
            Glide.with(this).load(loginData.getHead_pic()).into(mUserHead);
        } else {
            Glide.with(this).load(R.mipmap.user_head).into(mUserHead);
        }
        //
        if (!TextUtils.isEmpty(loginData.getNickName())) {
            mNickName.setText(loginData.getNickName());
        }
        //
        String gender = loginData.getGender();
        if (!TextUtils.isEmpty(gender)) {
            if ("1".equals(gender)) {
                mGender.setText(getString(R.string.male));
            } else {
                mGender.setText(getString(R.string.female));
            }
        }
        //生日
        birthday = loginData.getBirthday();
        if (!TextUtils.isEmpty(birthday)) {
            try {
                String constellation = ConstellationUtils.queryConstellation(Integer.parseInt(birthday.split("-")[1].trim()), Integer.parseInt(birthday.split("-")[2].trim()));
                mBirthday.setText(String.valueOf(birthday + " " + constellation));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        //用户id
        mId.setText(String.valueOf(loginData.getId()));

        //绑定手机
        String phone = loginData.getPhone();
        if (TextUtils.isEmpty(phone)) {
            mBindPhone.setText("未绑定");
        } else {
            mBindPhone.setText(phone);
        }

        //登录方式  先隐藏

        // 我的等级
        mLevel.setText(String.valueOf("Lv" + String.valueOf(loginData.getUserLevel())));
    }

    @Override
    protected void initPresenter() {
        presenter = new UserInfoPresenter(this);
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_user_info;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case Constant.REQUEST_HEAD:
                    break;
                case Constant.REQUEST_NICKNAME:
                    if (data != null) {
                        presenter.updateNickname(data.getStringExtra("nickname"));
                    }
                    break;
                case Constant.REQUEST_BIRTHDAY:
                    if (data != null) {
                        birthday = data.getStringExtra("birthday");
                        String constellation = data.getStringExtra("constellation");
                        Log.i("BirthdayActivity", "onActivityResult: " + birthday + constellation);
                        PreferenceUtil.getInstance(this).loadLoginData().setBirthday(birthday + constellation);
                        mBirthday.setText(birthday + constellation);
                    }
                    break;
                case Constant.REQUEST_SIGN:
                    if (data != null) {
                        presenter.updateSign(data.getStringExtra("sign"));
                    }
                    break;
            }
        }
    }

    @OnClick({R.id.user_head, R.id.user_nickname, R.id.user_gender, R.id.user_birthday, R.id.user_id, R.id.user_bind, R.id.user_login_type, R.id.user_level})
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.user_head:
                //设置头像
                showUserHeadImgChoiceFragment();
                break;
            case R.id.user_nickname:
                if (isNetwork()) {
                    NicknameSettingActivity.startActivity(this);
                }
                break;
            case R.id.user_gender:
                if (isNetwork()) {
                    showGenderChoiceFragment();
                }
                break;
            case R.id.user_birthday:
                if (isNetwork()) {
                    BirthdayActivity.startActivity(this, birthday);
                }
                break;
            case R.id.user_id:
                break;
            case R.id.user_bind:
                if (isNetwork()) {
                    PhoneBindActivity.startActivity(this);
                }
                break;
            case R.id.user_login_type:
                break;
            case R.id.user_level:
//                VipLevelActivity.startActivity(this);
                break;
        }
    }

    public static void start(Context context) {
        context.startActivity(new Intent(context, UserInfoActivity.class));
    }

    public static void start(Context context, String photoUrl) {
        Intent starter = new Intent(context, UserInfoActivity.class);
        starter.putExtra("photo_url", photoUrl);
        context.startActivity(starter);
    }

    @Override
    public Context getViewContext() {
        return this;
    }

    @Override
    public void headUpdate() {

    }

    @Override
    public void nicknameUpdate(String nickName) {
        mNickName.setText(nickName);
    }

    @Override
    public void birthdayUpdate(String birthday) {
        if (!TextUtils.isEmpty(birthday)) {
            String constellation = ConstellationUtils.queryConstellation(Integer.parseInt(birthday.split("-")[1]), Integer.parseInt(birthday.split("-")[2]));
            mBirthday.setText(String.valueOf(birthday + " " + constellation));
        }
    }

    @Override
    public void signUpdate(String sign) {

    }

    @Override
    public void genderUpdate(String gender) {
        if (!TextUtils.isEmpty(gender)) {
            if ("1".equals(gender)) {
                mGender.setText(getString(R.string.male));
                PreferenceUtil.getInstance(UserInfoActivity.this).saveUserGender(1);
            } else {
                mGender.setText(getString(R.string.female));
                PreferenceUtil.getInstance(UserInfoActivity.this).saveUserGender(2);
            }
        }
        EventBus.getDefault().post(new RefreshStoreEvent());
    }

    public void updateGenderFromFragment(String gender) {
        removeGenderChoiceFragment();
        presenter.updateGender(gender);
    }


    private void showUserHeadImgChoiceFragment() {
        if (mUserHeadImgChoiceFragment == null) {
            mUserHeadImgChoiceFragment = new UserHeadImgChoiceFragment();
        }
        if (!mUserHeadImgChoiceFragment.isAdded() && !mUserHeadImgChoiceFragment.isVisible() && !mUserHeadImgChoiceFragment.isRemoving()) {
            mUserHeadImgChoiceFragment.show(getSupportFragmentManager(), "mUserHeadImgChoiceFragment");
        }
    }

    private void showGenderChoiceFragment() {
        if (mGenderChoiceFragment == null) {
            mGenderChoiceFragment = new GenderChoiceFragment();
        }
        if (!mGenderChoiceFragment.isAdded() && !mGenderChoiceFragment.isVisible() && !mGenderChoiceFragment.isRemoving()) {
            mGenderChoiceFragment.show(getSupportFragmentManager(), "mGenderChoiceFragment");
        }
    }

    private void removeGenderChoiceFragment() {
        if (mGenderChoiceFragment != null) {
            mGenderChoiceFragment.dismiss();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void setUserIcon(File file) {
        if (file == null) {
            ToastUtil.makeShortToast("空文件，请重新拍摄！");
            return;
        }
        presenter.updateHead(file);
    }
}
